import React, { Component } from 'react';
import {Link} from 'react-router';
import Split from '../CommonComponent/Split'
import Footer from '../CommonComponent/Footer'
import IsShowEmptyImg from '../CommonComponent/IsShowEmptyImg'
import StoreRow from '../../Component/Malls/StoreRow';
import {saveToken,loadToken,GetQueryString,getToken,bodyScroll} from '../../Action/rpc';
import {ProductList,AgentProductList,MyInfo,WxLogin} from '../../Action/auth';
import $ from "jquery";
import iScroll from "iscroll/build/iscroll-probe";
import {initWx,initWxShare} from '../../Action/wxUtil';
import '../../Stylesheets/wx/common.css';
import '../../Stylesheets/wx/homePage.css';

export default class ShareMalls extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            name:'',
            img:'',
            agentName:'',
            stepName:'',
            isActive:'',
            grade:0,
            listPage:1,
            goodsList:''
        };
        this.page = 1;
        this.list=[];
        this.loadingStep = 0;
    }

    async componentWillMount() {
        if(loadToken()){

        }else if(GetQueryString('code')){
            await this.getShareToken()
        }
        await this.getMyInfo();
        await this.getProductList(0,1,this.refs.search.value);
        this.myScroll.refresh();
    }

    async getShareToken(){
        await WxLogin(GetQueryString('code'))
            .then(res=>{
                const token = res.token;
                sessionStorage.setItem('openId',res.openId)
                saveToken(token)
            })
            .catch(err=>{
                alert(err)
                console.log(err)
            })
    }

    componentDidMount() {
        document.querySelector('body').addEventListener('touchmove',bodyScroll, false);

        var pullDownEl = $('#pullDown');
        pullDownEl['class'] = pullDownEl.attr('class');
        pullDownEl.attr('class','').hide();

        var pullUpEl = $('#pullUp');
        pullUpEl['class'] = pullUpEl.attr('class');
        pullUpEl.attr('class','').hide();

        this.myScroll = new iScroll('#content', {
            preventDefault: false,
            probeType: 2,//probeType：1对性能没有影响。在滚动事件被触发时，滚动轴是不是忙着做它的东西。probeType：2总执行滚动，除了势头，反弹过程中的事件。这类似于原生的onscroll事件。probeType：3发出的滚动事件与到的像素精度。注意，滚动被迫requestAnimationFrame（即：useTransition：假）。
            scrollbars: true,//有滚动条
            mouseWheel: true,//允许滑轮滚动
            fadeScrollbars: true,//滚动时显示滚动条，默认影藏，并且是淡出淡入效果
            bounce:true,//边界反弹
            interactiveScrollbars:true,//滚动条可以拖动
            shrinkScrollbars:'scale',// 当滚动边界之外的滚动条是由少量的收缩。'clip' or 'scale'.
            click: true ,// 允许点击事件
            keyBindings:true,//允许使用按键控制
            momentum:true// 允许有惯性滑动
        });
        //滚动时
        this.myScroll.on('scroll', this.scroll );
        this.myScroll.on('touchmove', function(e){e.stopPropagation()});
        //滚动完毕
        this.myScroll.on('scrollEnd',this.scrollEnd );
    }

    scroll=()=>{
        var pullDownEl = $('#pullDown');
        var pullDownL = pullDownEl.find('.pullDownLabel');
        var pullUpEl = $('#pullUp');
        var pullUpL = pullUpEl.find('.pullUpLabel');

        if(this.loadingStep == 0 && !pullDownEl.attr('class').match('flip|loading') && !pullUpEl.attr('class').match('flip|loading')){
            if (this.myScroll.y > 5) {
                //下拉刷新效果
                pullDownEl.attr('class',pullUpEl['class'])
                pullDownEl.show();
                this.myScroll.refresh();
                pullDownEl.addClass('flip');
                pullDownL.html('下拉刷新...');
                this.loadingStep = 1;
            }else if (this.myScroll.y < (this.myScroll.maxScrollY - 5) && this.state.goodsList.length>0) {
                if(this.state.listPage!=this.page){
                    //上拉刷新效果
                    pullUpEl.attr('class',pullUpEl['class'])
                    pullUpEl.show();
                    this.myScroll.refresh();
                    pullUpEl.addClass('flip');
                    pullUpL.html('上拉加载...');
                    this.loadingStep = 1;
                }
            }
        }

    }
    scrollEnd=()=>{
        var pullDownEl = $('#pullDown');
        var pullDownL = pullDownEl.find('.pullDownLabel');
        var pullUpEl = $('#pullUp');
        var pullUpL = pullUpEl.find('.pullUpLabel');

        if(this.loadingStep == 1){
            if (pullUpEl.attr('class').match('flip|loading')) {
                pullUpEl.removeClass('flip').addClass('loading');
                pullUpL.html('Loading...');
                this.loadingStep = 2;
                this.pullUpAction();
            }else if(pullDownEl.attr('class').match('flip|loading')){
                pullDownEl.removeClass('flip').addClass('loading');
                pullDownL.html('Loading...');
                this.loadingStep = 2;
                this.pullDownAction();
            }
        }
    }

    pullDownAction() {//下拉事件
        var pullDownEl = $('#pullDown');
        var pullDownL = pullDownEl.find('.pullDownLabel');

        this.page=1;
        this.getProductList(0,this.page,this.refs.search.value)

        pullDownEl.removeClass('loading');
        pullDownL.html('下拉刷新...');
        pullDownEl['class'] = pullDownEl.attr('class');
        pullDownEl.attr('class','').hide();
        this.myScroll.refresh();
        this.loadingStep = 0;
    }
    pullUpAction() {//上拉事件
        var pullUpEl = $('#pullUp');
        var pullUpL = pullUpEl.find('.pullUpLabel');

        if(this.state.listPage>this.page){
            this.page++;
            this.getProductList(0,this.page,this.refs.search.value)
        }
        pullUpEl.removeClass('loading');
        pullUpL.html('上拉显示更多...');
        pullUpEl['class'] = pullUpEl.attr('class');
        pullUpEl.attr('class','').hide();
        this.myScroll.refresh();
        this.loadingStep = 0;
    }

    componentWillUnmount() {
        document.querySelector('body').removeEventListener('touchmove',bodyScroll, false);
    }

    async getMyInfo(){
        await MyInfo()
            .then(res=>{
                this.setState({isActive:res.IS_ACTIVE})
                this.setState({grade:res.AGENT_GRADE})
            })
    }

    async getProductList(status,page,name){
        const {grade}=this.state;
        if(grade>0){//进货列表
            await AgentProductList(status,page,name)
                .then(res=>{
                    const page = Math.ceil(res.total/res.pageSize);
                    this.setState({listPage:page})
                    if(page==1){
                        this.list = res.resultList;
                        this.setState({goodsList:this.list})
                    }else{
                        this.list = this.list.concat(res.resultList);
                        this.setState({goodsList:this.list})
                    }
                    this.myScroll.refresh();
                })
                .catch(err=>{
                    console.warn('err',err)
                })
        }else{//商品列表
            await ProductList(status,page,name)
                .then(res=>{
                    const page = Math.ceil(res.total/res.pageSize);
                    this.setState({listPage:page})
                    if(page==1){
                        this.list = res.resultList;
                        this.setState({goodsList:this.list})
                    }else{
                        this.list = this.list.concat(res.resultList);
                        this.setState({goodsList:this.list})
                    }
                    this.myScroll.refresh();
                })
                .catch(err=>{
                    console.warn('err',err)
                })
        }

    }

    search(){
        const {grade}=this.state;
        this.getProductList(0,1,this.refs.search.value)
    }

    render(){
        const {goodsList}=this.state;
        return(
            <div>
                <div className="flex width100 flex-align-center flex-pack-center f20 colorfff h50 pf bgDefault searchContent">
                    <div style={{height:30,borderBottom:'1px solid #fff',width:'90%'}}
                         className="flex flex-align-center flex-pack-center f16">
                        <input ref="search" type="text" placeholder="请输入搜索内容"
                               style={{border:0,paddingLeft:5}}
                               className="flex-1 bgDefault"/>
                        <span className="f16"
                              style={{border:0,background:'transparent',padding:'2px 5px 2px 10px'}}
                              onClick={()=>this.search()}
                        >搜索</span>
                    </div>
                </div>
                <div id="content" className="bkg_color" style={{top:50,bottom:0}}>
                    <div id="scroller" style={{minHeight:window.innerHeight-99}}>
                        <div id="pullDown" className="ub ub-pc c-gra">
                            <div className="pullDownIcon"></div>
                            <div className="pullDownLabel">下拉刷新</div>
                        </div>
                        <ul id="add">
                            {
                                goodsList == ''?
                                    <IsShowEmptyImg
                                        styleSheet={{width:69,height:72,marginTop:120}}
                                        title={'查询列表是空的哦~'}
                                    />
                                    :
                                goodsList&&goodsList.map((el,index)=>{
                                    return (
                                        <Link to = {'/goodsDesc'} query = {{id:el.ID}}>
                                            <StoreRow
                                                title = {el.NAME}
                                                price = {el.CURRENT_PRICE}
                                                imgurl = {el.IMAGE}
                                                sales = {el.SALES}
                                                showBorderBottom = {true}
                                            />
                                        </Link>
                                    )
                                })
                            }
                            <div style={{clear:'both'}}></div>
                        </ul>
                        <div id="pullUp" className="ub ub-pc c-gra">
                            <div className="pullUpIcon"></div>
                            <div className="pullUpLabel">上拉显示更多...</div>
                        </div>
                    </div>
                </div>
                <div className=" df border_top pf bottom0 width100 flex" style={{zIndex:1000}}>
                    <div
                        className="width_100 flex-1 flex flex-pack-center bkg_footer "
                       >
                        <Link
                            to='/shareShopCarts'
                            className="di df flex-v flex1 flex-align-center color99 width100"
                        >
                            <div style={{height:25}} className="tc">
                                <span className='di footerNav' style={{lineHeight:0}}>
                                    <img src={require("../../Images/Index/shoppingCartActive.png")} />
                                </span>
                            </div>
                            <div style={{height:22,lineHeight:'22px'}} className='colorlv f12 tc'>进入购物车</div>
                        </Link>
                    </div>
                </div>
            </div>
        )
    }
}
